import axios from 'axios'
import store from '@/store'
import router from '@/router'
import { Message } from 'element-ui'
import { getTimeStamp } from '@/utils/auth'
const service = axios.create({
  // process.env. 为环境变量
  baseURL: process.env.VUE_APP_BASE_API, // 执行 npm run dev 走 /api 开发环境路线 执行 npm run build 走 /prod-api 生产环境路线
  timeout: 5000 // 设置超时时间
})
const timeOut = 7200
service.interceptors.request.use(config => {
  if (store.getters.token) {
    if (isCheckTimeStamp()) {
      store.dispatch('user/logout')
      router.push('/login')
      return Promise.reject(new Error('token超时了'))
    }
    config.headers['Authorization'] = `Bearer ${store.getters.token}`
  }
  return config
}, error => {
  return Promise.reject(error)
})
service.interceptors.response.use(response => {
  const { success, message, data } = response.data
  if (success) {
    return data
  } else {
    Message.error(message)
  }
  return Promise.reject(new Error(message))
}, error => {
  // 被动介入token
  if (error.response && error.response.data && error.response.data.code === 10002) {
    store.dispatch('user/logout')
    router.push('/login')
  } else {
    Message.error(error.message)
  }
  return Promise.reject(error)
})
function isCheckTimeStamp() {
  const timeStamp = Date.now()
  return (timeStamp - getTimeStamp()) / 1000 > timeOut
}
export default service
